package com.ourteam.frame.web;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class DateConverter implements WebBindingInitializer {

	private final static String[] DATE_TIME = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm" };

	private final static String[] DATE = new String[] { "yyyy-MM-dd" };

	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {

		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		final SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true) {

			@Override
			public void setAsText(String arg0) throws IllegalArgumentException {
				if (StringUtils.isNotBlank(arg0)) {
					try {
						if (arg0.indexOf(":") != -1) {
							setValue(DateUtils.parseDate(arg0, DATE_TIME));
						} else {
							setValue(DateUtils.parseDate(arg0, DATE));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				} else {
					super.setAsText(arg0);
				}

			}
		});

		binder.registerCustomEditor(Timestamp.class, new CustomDateEditor(datetimeFormat, true));

	}

}
